package com.wl.msm.service.impl;

import com.wl.msm.service.MsmService;
import com.wl.msm.utils.RLYMsm;
import com.wl.msm.utils.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lei.wan
 * @since 2021/9/2
 */
@Service
public class MsmServiceImpl implements MsmService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Map<String,Object> sendMsm(String phone) {
        HashMap<String, Object> map = new HashMap<>();
        String code1 = redisTemplate.opsForValue().get(phone);
        String sms = "";
        if(StringUtils.isEmpty(code1)){
            String code = RandomUtil.getFourBitRandom();
            sms = RLYMsm.sms(phone, code);
            if(code.equals(sms)){
                redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
                map.put("status",true);
                map.put("code",code);
            }else{
                map.put("status",false);
                map.put("error",sms);
            }
        }else{
            map.put("status",true);
        }
        return map;
    }
}
